package com.lagou.web.server;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

import java.io.File;
import java.io.IOException;

/**
 *
 *
 * @author huangzl
 * @date 2021/7/21
 */
public class TomcatWebServer implements WebServer {

	private int port = 8080;

	public int getPort() {
		return this.port;
	}

	public TomcatWebServer() {
		// 创建tomcat实例，用来启动tomcat
		Tomcat tomcat = new Tomcat();
		File baseDir = this.createTempDir("tomcat");
		// tomcat存储自身信息的目录，比如日志等信息，根目录
		tomcat.setBaseDir(baseDir.getAbsolutePath());
		// 设置协议
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setPort(getPort());
		connector.setProperty("bindOnInit", "false");
		tomcat.getService().addConnector(connector);
		tomcat.setConnector(connector);
		// 是否设置自动部署
		tomcat.getHost().setAutoDeploy(false);
		// 设置端口
		tomcat.setPort(getPort());
		try {
			//设置WEB-INF文件夹所在目录
			tomcat.addWebapp("/", baseDir.getAbsolutePath());
			// 启动tomcat
			tomcat.start();
			// 维持tomcat服务，否则tomcat一启动就会关闭
			tomcat.getServer().await();
		} catch (Exception var6) {
			var6.printStackTrace();
		}
	}

	protected final File createTempDir(String prefix) {
		try {
			File tempDir = File.createTempFile(prefix + ".", "." + getPort());
			tempDir.delete();
			tempDir.mkdir();
			tempDir.deleteOnExit();
			return tempDir;
		} catch (IOException var3) {
			var3.printStackTrace();
		}
		return null;
	}
}
